<template>
  <div id="ConstructionLog">
    <p class="title" style="padding: 0 10px">
      <span class="line"></span>
      施工日志
    </p>
    <div v-for="(item, index) in listData" :key="index">
      <p
        style="
          padding: 10px;
          font-weight: bold;
          display: flex;
          align-items: center;
        "
      >
        <span class="line"></span>
        {{ item.name }}
      </p>
      <div
        v-for="(item1, index1) in item.children"
        :key="index1"
        style="width: 100vw; overflow: auto"
      >
        <p style="padding-left: 10px">{{ item1.name }}</p>
        <van-uploader
          @click-upload="getList(item1)"
          :after-read="afterRead"
          :before-delete="delectFile"
          v-model="item1.fileList"
          multiple
        />
      </div>
    </div>
    <van-button
      v-if="!$route.query.type"
      @click="saveData"
      round
      block
      type="info"
      native-type="submit"
      >确定</van-button
    >
  </div>
</template>

<script>
import {
  FileServerUpload,
  InsertDataView,
  DelectFile,
  Data,
  dataServerOpenDataView,
  insertDataView,
  updateDataView,
  FileServerProxy,
  dataTransFile,
  dataTransFilePreview
} from "../../utils/api";

export default {
  name: "ConstructionLog",
  data() {
    return {
      tableData: "",
      listData: [
        {
          name: "放样",
          children: [
            {
              name: "四边长度",
              groupGuid: "b9bcaba3-82f1-4c9b-8585-9ec7d0d7aed6",
              fileList: [],
            },
          ],
        },
        {
          name: "地基钢筋",
          children: [
            {
              name: "规格寄照片",
              groupGuid: "e1949021-c239-4473-95d0-35b260103e2f",
              fileList: [],
            },
          ],
        },
        {
          name: "基础",
          children: [
            {
              name: "轴线尺寸",
              groupGuid: "8c853bca-2a3d-4a73-b7b6-34ea098b2ce0",
              fileList: [],
            },
            {
              name: "混凝土强度",
              groupGuid: "816f51d2-1f28-4fe3-8679-75b21503fbed",
              fileList: [],
            },
            {
              name: "防水",
              groupGuid: "6db48286-81df-49e6-89d7-ee48b915931a",
              fileList: [],
            },
            {
              name: "管线预埋",
              groupGuid: "509b147c-c6dc-43f0-8477-3a6bee96874a",
              fileList: [],
            },
            {
              name: "结构预埋件",
              groupGuid: "7c2d50e1-3499-4173-a6ee-782b75949d74",
              fileList: [],
            },
          ],
        },
        {
          name: "一层",
          children: [
            {
              name: "层高",
              groupGuid: "3e319216-491b-42e7-9b49-502eec61a6c8",
              fileList: [],
            },
            {
              name: "楼面尺寸",
              groupGuid: "11c1ce8f-601b-4e83-aec8-309de8b88ce7",
              fileList: [],
            },
            {
              name: "梁柱及板钢筋照片",
              groupGuid: "b717d43e-cc51-4647-a096-f017dd236062",
              fileList: [],
            },
          ],
        },
        {
          name: "二层",
          children: [
            {
              name: "层高",
              groupGuid: "1fadb4fd-87ee-456c-a19c-04d7f2526615",
              fileList: [],
            },
            {
              name: "楼面尺寸",
              groupGuid: "37afcffe-26a5-40a3-ac6d-0a36ef16fde9",
              fileList: [],
            },
            {
              name: "梁柱及板钢筋照片",
              groupGuid: "691c6c0f-8baa-4425-8211-f2f9bee429dc",
              fileList: [],
            },
          ],
        },
        {
          name: "三层",
          children: [
            {
              name: "层高",
              groupGuid: "71081664-56ba-4676-b14c-b569b181153f",
              fileList: [],
            },
            {
              name: "楼面尺寸",
              groupGuid: "c5b125ad-21a9-4768-b60f-e8038d89e3a9",
              fileList: [],
            },
            {
              name: "梁柱及板钢筋照片",
              groupGuid: "51483c72-cf2b-4962-b654-13bb718762a3",
              fileList: [],
            },
          ],
        },
        {
          name: "结顶",
          children: [
            {
              name: "顶高",
              groupGuid: "8486d5b6-4b96-4b9b-96b3-8a3c80fae57c",
              fileList: [],
            },
            {
              name: "檐口高",
              groupGuid: "2bb5cf21-d68f-47c4-8e1f-2fb3218f9d09",
              fileList: [],
            },
            {
              name: "滴水尺寸",
              groupGuid: "5d79e0f3-3acf-4ed9-8dc3-14dbc96d955b",
              fileList: [],
            },
            {
              name: "房屋坡度",
              groupGuid: "2ac8070b-787d-4fe5-a788-3049e59aaebc",
              fileList: [],
            },
            {
              name: "避雷",
              groupGuid: "fe9109db-3b5e-4cd8-abcd-be0cdb937270",
              fileList: [],
            },
          ],
        },
        {
          name: "外立面",
          children: [
            {
              name: "四周照片",
              groupGuid: "8978af55-f704-4d68-b660-3de9817dc42c",
              fileList: [],
            },
          ],
        },
        {
          name: "隐蔽工程",
          children: [
            {
              name: "水电",
              groupGuid: "91047b97-80ac-47c7-a2d5-bd708d1f1ec0",
              fileList: [],
            },
            {
              name: "防水",
              groupGuid: "d525a87f-dd62-4c1d-93c3-b376cac502b9",
              fileList: [],
            },
          ],
        },
      ],
      groupGuids: "",
      rowGuid: "",
      isSave: false,
      rowGuid1: "",
    };
  },
  methods: {
    getList(item) {
      this.groupGuids = item.groupGuid;
    },
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      this.getFileServerUpload(file.file);
    },
    delectFile: async function (file) {
      // if (file.ROW_GUID) {
      //   const res = await DelectFile({
      //     fileGuid: file.ROW_GUID,
      //     token: window.localStorage.getItem("token"),
      //   });
      // }
      let fileguid = "";
      if (file.ROW_GUID) {
        fileguid = file.ROW_GUID;
      } else {
        fileguid = this.fileGuid;
      }
      if (fileguid) {
        let params = {
          accessCode: "ce9b691634de4ebca68dc5bb638d07f4",
             cityCode: window.localStorage.getItem("citycode")
              ? window.localStorage.getItem("citycode")
              : "441300000000",
          params: {
            fileGuid: fileguid,
            token: window.localStorage.getItem("token"),
          },
        };
        const res = await FileServerProxy(params);
        let data = JSON.parse(res.data.data).Success;
        if (data) {
          this.$toast.success("删除成功!");
        }
      }
    },
    getFileServerUpload: async function (file) {
      // let formData = new FormData();
      // formData.append("file", file);
      // formData.append("toRowGuid", this.rowGuid);
      // formData.append("groupGuid", this.groupGuids);
      // formData.append("token", window.localStorage.getItem("token"));
      // const res = await FileServerUpload(formData);
      // if (res.data.Success == true) {
      //   this.$notify({ type: "success", message: "上传成功!" });
      // }
      let data = {
        toRowGuid: this.rowGuid,
        groupGuid: this.groupGuids,
        token: window.localStorage.getItem("token"),
      };
      let formData = new FormData();
      formData.append("file", file);
      formData.append("accessCode", "7a3fc061c866434b8475d3775c9ddcea");
      formData.append("cityCode",  window.localStorage.getItem("citycode")
              ? window.localStorage.getItem("citycode")
              : "441300000000");
      formData.append("token", window.localStorage.getItem("token"));
      formData.append("paramStr", JSON.stringify(data));
      const res = await dataTransFile(formData);
      let data1 = JSON.parse(res.data.data).FileList;
      this.fileGuid = data1[0].FILEGUID;
      if (data1[0].FILEGUID) {
        this.$toast.success("上传成功!");
      }
    },
    getNowTime: function () {
      let dateTime;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      return dateTime;
    },
    saveData: async function () {
      // (this.isSave)
      if (this.isSave) {
        let tableDatas = [
          {
            housecode: this.tableData.FAMILYHOUSEID,
            TBR: JSON.parse(window.localStorage.getItem("userName")).userName,
            createtime: this.getNowTime(),
            TO_ROW_GUID: this.tableData.ROW_GUID,
            ROW_GUID: this.rowGuid,
          },
        ];
        // let params = {
        //   dataGuid: "b0f8aba8-8927-4c89-9703-ed969367d9b1",
        //   strParams: JSON.stringify(tableDatas),
        //   token: window.localStorage.getItem("token"),
        // };
        // const res1 = await InsertDataView(params);
        // if (res1.data.Success) {
        //   this.$notify({ type: "success", message: "保存成功!" });
        //   this.isSave = false;
        // }
        let params = {
          accessCode: "0fb3f6123d1b4fe6851c99532c463f6f",
             cityCode: window.localStorage.getItem("citycode")
              ? window.localStorage.getItem("citycode")
              : "441300000000",
          params: {
            dataGuid: "b0f8aba8-8927-4c89-9703-ed969367d9b1",
            strParams: JSON.stringify(tableDatas),
            token: window.localStorage.getItem("token"),
          },
        };
        const res = await FileServerProxy(params);
        let data = JSON.parse(res.data.data).Success;
        if (data) {
          this.$notify({ type: "success", message: "保存成功!" });
        }
      } else {
        this.$notify({ type: "success", message: "保存成功!" });
      }
    },
    getFile: async function () {
      let groupGuid = [];
      this.listData.forEach((item) => {
        item.children.forEach((items) => {
          groupGuid.push(items.groupGuid);
        });
      });
      // const res1 = await GetFileData({
      //   groupGuid: groupGuid.join(","),
      //   toRowGuid: this.rowGuid,
      // });
      // if (res1.data.FilesInfo.length > 0) {
      //   res1.data.FilesInfo.forEach((element) => {
      //     this.listData.forEach((item) => {
      //       item.children.forEach((items) => {
      //         if (element.GROUPGUID == items.groupGuid) {
      //           element["isImage"] = true;
      //           element["url"] =
      //             window.g.BaseURL +
      //             "FileServer/api/Preview?token=" +
      //             window.localStorage.getItem("token") +
      //             "&" +
      //             "fileGuid=" +
      //             encodeURIComponent(element.ROW_GUID);
      //           items.fileList.push(element);
      //         }
      //       });
      //     });
      //   });
      // }
      let params = {
        accessCode: "1fdcbce42c6d4748a020feba618d54b8",
           cityCode: window.localStorage.getItem("citycode")
              ? window.localStorage.getItem("citycode")
              : "441300000000",
        params: {
          groupGuid: groupGuid.join(","),
          toRowGuid: this.rowGuid,
          token: window.localStorage.getItem('token')
        },
      };
      const res = await FileServerProxy(params);
      let data = JSON.parse(res.data.data).FilesInfo;
      if (data.length > 0) {
        ;
        data.forEach((element) => {
          this.listData.forEach((items) => {
            if (items.children.length > 0) {
              items.children.forEach((cc) => {
                if (element.GROUPGUID == cc.groupGuid) {
                  this.getFileUrl(element, cc);
                  // element["isImage"] = true;
                  // element["url"] =
                  //   window.g.BaseURL +
                  //   "FileServer/api/Preview?token=" +
                  //   window.localStorage.getItem("token") +
                  //   "&" +
                  //   "fileGuid=" +
                  //   encodeURIComponent(element.ROW_GUID);
                  //   cc.fileList.push(element);
                }
              });
            } else {
              if (element.GROUPGUID == items.groupGuid) {
                 this.getFileUrl(element, items);
                // element["isImage"] = true;
                // element["url"] =
                //   window.g.BaseURL +
                //   "FileServer/api/Preview?token=" +
                //   window.localStorage.getItem("token") +
                //   "&" +
                //   "fileGuid=" +
                //   encodeURIComponent(element.ROW_GUID);
                // items.fileList.push(element);
              }
            }
          });
        });
      }
    },
    getFileUrl: async function (element, item) {
      let formData = new FormData();
      formData.append("accessCode", "98bcf528966e48ce896a8b3fd02d45d5");
      formData.append(
        "cityCode",
        window.localStorage.getItem("citycode")
          ? window.localStorage.getItem("citycode")
          : "441300000000"
      );
      formData.append(
        "paramStr",
        JSON.stringify({
          fileGuid: element.ROW_GUID,
        })
      );
      let response = await dataTransFilePreview(formData);
      if (response) {
        var img = new Blob([new Int8Array(response.data, 0)], {
          type: response.headers["content-type"],
        }); //type类型可自定义
        element["isImage"] = true;
        element["url"] = window.URL.createObjectURL(img);
        item.fileList.push(element);
      }
    },
    //查询施工日志表
    getData: async function () {
      // let dataGuid = "b0f8aba8-8927-4c89-9703-ed969367d9b1";
      // let searchObject = encodeURIComponent(
      //   JSON.stringify([
      //     { field: "to_row_guid", value: this.rowData.ROW_GUID, operator: "=" },
      //   ])
      // );
      // let token = window.localStorage.getItem("token");
      // const res = await dataServerOpenDataView(dataGuid, searchObject, token);
      // if (res.data.Data.length > 0) {
      //   this.isSave = false;
      //   this.getFile();
      // } else {
      //   this.isSave = true;
      // }
      let params = {
        accessCode: "688bd3883572440a859dfd8ba9194e7b",
           cityCode: window.localStorage.getItem("citycode")
              ? window.localStorage.getItem("citycode")
              : "441300000000",
        params: {
          dataguid: "b0f8aba8-8927-4c89-9703-ed969367d9b1",
          searchObject: JSON.stringify([
            {
              field: "to_row_guid",
              value: this.rowData.ROW_GUID,
              operator: "=",
            },
          ]),
          token: window.localStorage.getItem("token"),
        },
      };
      const res = await FileServerProxy(params);
      let data = JSON.parse(res.data.data).Data;
      if (data.length > 0) {
        this.isSave = false;
        this.getFile();
      } else {
        this.isSave = true;
      }
    },
    newGuid(format) {
      //表示全局唯一标识符 (GUID)。
      function Guid(g) {
        var arr = new Array(); //存放32位数值的数组
        if (typeof g == "string") {
          //如果构造函数的参数为字符串
          InitByString(arr, g);
        } else {
          InitByOther(arr);
        }
        //返回 Guid 类的此实例值的 String 表示形式。
        this.ToString = function (format) {
          if (typeof format == "string") {
            if (
              format == "N" ||
              format == "D" ||
              format == "B" ||
              format == "P"
            ) {
              return ToStringWithFormat(arr, format);
            } else {
              return ToStringWithFormat(arr, "D");
            }
          } else {
            return ToStringWithFormat(arr, "D");
          }
        };

        //由字符串加载
        function InitByString(arr, g) {
          g = g.replace(/\{|\(|\)|\}|-/g, "");
          g = g.toLowerCase();
          if (g.length != 32 || g.search(/[^0-9,a-f]/i) != -1) {
            InitByOther(arr);
          } else {
            for (var i = 0; i < g.length; i++) {
              arr.push(g[i]);
            }
          }
        }

        //由其他类型加载
        function InitByOther(arr) {
          // var i = 32;
          // while (i--) {
          //     arr.push("0");
          // }

          var i = 32;
          while (i--) {
            arr.push(Math.floor(Math.random() * 16.0).toString(16));
          }
        }

        /*
              根据所提供的格式说明符，返回此 Guid 实例值的 String 表示形式。
              N  32 位： xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
              D  由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
              B  括在大括号中、由连字符分隔的 32 位数字：{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
              P  括在圆括号中、由连字符分隔的 32 位数字：(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
              */

        //增加一个标识能区分开这个guid是不是由前端生成的
        function ToStringWithFormat(arr, format) {
          switch (format) {
            case "N":
              return arr.toString().replace(/,/g, "");
            case "D":
              var str =
                arr.slice(0, 8) +
                "-1203" +
                "-" +
                arr.slice(12, 16) +
                "-" +
                arr.slice(16, 20) +
                "-" +
                arr.slice(20, 32);
              str = str.replace(/,/g, "");
              return str;
            case "B":
              var str = ToStringWithFormat(arr, "D");
              str = "{" + str + "}";
              return str;
            case "P":
              var str = ToStringWithFormat(arr, "D");
              str = "(" + str + ")";
              return str;
            default:
              return new Guid();
          }
        }

        return this.ToString();
      }

      var g = new Guid();
      return g.ToString(format);
    },
  },
  mounted() {
    // this.rowGuid = "80ef66da-1203-29a1-6052-d7335c455a53"
    this.tableData = JSON.parse(this.$route.query.data);
    this.rowData = JSON.parse(this.$route.query.data);
    //查询

    this.rowGuid = this.rowData.ROW_GUID;

    // if( this.rowGuid1){
    //   this.isSave = false
    // }

    this.getData();
    //wjh 2022-02-26  先查询日志表看有没有记录
  },
};
</script>

<style scoped lang="scss">
#ConstructionLog {
  height: 100vh;
  overflow: auto;
  font-size: 16px;
  .line {
    width: 6px;
    height: 26px;
    background: #3f8ffc;
    display: inline-block;
    margin-right: 10px;
  }
  .title {
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-size: 20px;
    position: relative;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #9b9b9b;
  }
}
</style>
